package com.zhizhi.util;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.zhizhi.common.constant.SystemConstant;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * description: 加密解密工具类 <br>
 * date: 2020/7/23 10:19 <br>
 * author: Mr.Yu <br>
 */
public class CryptoUtil {


    /**
     * AES/ECB/PKCS7 padding加密
     * Key:已定义
     * value：需要对加密的字符串做URL编码
     * @param data
     * @return
     */
    public static String aesCbcPkcs7PaddingEncryption (String data) {
        byte[] keyByteArray = SystemConstant.KEY_AES.getBytes();
        SymmetricCrypto aes = new SymmetricCrypto("AES/ECB/PKCS7Padding", keyByteArray);
        return aes.encryptBase64(data);
    }

    /**
     * 转换成十六进制字符串
     *
     * @param
     * @return lee on 2017-08-09 10:54:19
     */
    public static byte[] hex(String key) {
        String f = DigestUtils.md5Hex(key);
        byte[] bkeys = new String(f).getBytes();
        byte[] enk = new byte[24];
        for (int i = 0; i < 24; i++) {
            enk[i] = bkeys[i];
        }
        return enk;
    }

    /**
     * 3DES加密
     *
     * @param key    密钥，24位
     * @param srcStr 将加密的字符串
     * @return lee on 2017-08-09 10:51:44
     */
    public static String encode3Des(String key, String srcStr) {
        byte[] keybyte = hex(key);
        byte[] src = srcStr.getBytes();
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
            //加密
            Cipher c1 = Cipher.getInstance("DESede");
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            String pwd = Base64.encodeBase64String(c1.doFinal(src));
            return pwd;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 3DES解密
     *
     * @param key    加密密钥，长度为24字节
     * @param desStr 解密后的字符串
     * @return lee on 2017-08-09 10:52:54
     */
    public static String decode3Des(String key, String desStr) {
        Base64 base64 = new Base64();
        byte[] keybyte = hex(key);
        byte[] src = base64.decode(desStr);

        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
            //解密
            Cipher c1 = Cipher.getInstance("DESede");
            c1.init(Cipher.DECRYPT_MODE, deskey);
            String pwd = new String(c1.doFinal(src));
            return pwd;
        } catch (Exception e) {
            return null;
        }
    }
}